import pino from 'pino';
import { existsSync, mkdirSync } from 'fs';
import { join } from 'path';

// 创建日志目录
const ensureLogDir = (dirPath) => {
  if (!existsSync(dirPath)) {
    mkdirSync(dirPath, { recursive: true });
  }
  return dirPath;
};

// 基础配置
const baseConfig = {
  level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
  messageKey: 'msg', 
  nestedKey: 'payload',
  formatters: {
    level: (label) => ({ level: label }),
    bindings: (bindings) => ({
      pid: bindings.pid,
      hostname: bindings.hostname,
      node_version: process.version
    })
  },
  mixin: () => ({})
};

// 动态创建Transport
let transport;
if (process.env.NODE_ENV === 'development') {
  transport = pino.transport({
    target: 'pino-pretty',
    options: {
      colorize: true,
      translateTime: 'SYS:yyyy-mm-dd HH:MM:ss',
      ignore: 'pid,hostname',
      messageFormat: '{context.reqId} - {msg}'
    }
  });
} else {
  const logDir = ensureLogDir('./logs');
  transport = pino.transport({
    targets: [
      {
        target: 'pino/file',
        level: 'error',
        options: { destination: join(logDir, 'error.log') }
      },
      {
        target: 'pino-roll',
        options: {
          file: join(logDir, 'app.log'),
          frequency: 'daily'
        }
      }
    ]
  });
}

// 创建日志实例
const logger = pino(baseConfig, transport);

// 增强方法
export default {
  ...logger,

  // 错误日志增强
  error(error, message = 'Server Error') {
    this[error.level || 'error']({
      message,
      stack: error.stack,
      code: error.code,
      details: error.details
    }, error.message);
  },

  // HTTP请求日志
  httpLog(ctx, responseTime) {
    this.info({
      method: ctx.method,
      path: ctx.path,
      status: ctx.status,
      duration: responseTime,
      userAgent: ctx.headers['user-agent']
    }, 'HTTP Request');
  },

  // 审计日志
  audit(action, metadata = {}) {
    this.info({
      type: 'AUDIT',
      action,
      userId: metadata.userId,
      resourceId: metadata.resourceId
    }, `User Action: ${action}`);
  }
};

// 未捕获异常处理
process.on('uncaughtException', (err) => {
  logger.fatal(err, 'Uncaught Exception');
  process.exit(1);
});

process.on('unhandledRejection', (reason) => {
  logger.fatal(reason, 'Unhandled Rejection');
  process.exit(1);
});